package com.windoent.yugioh.ui.activity.saishi;

import android.Manifest;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.baidu.mobstat.StatService;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.windoent.yugioh.R;
import com.windoent.yugioh.adapter.city.CityListAdapter;
import com.windoent.yugioh.adapter.city.ResultListAdapter;
import com.windoent.yugioh.base.BaseActivity;
import com.windoent.yugioh.constants.LocateState;
import com.windoent.yugioh.help.db.City;
import com.windoent.yugioh.help.db.DBManager;
import com.windoent.yugioh.utils.LogUtils;
import com.windoent.yugioh.utils.PickerStringUtils;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.widget.ActivityTitle;
import com.windoent.yugioh.widget.SideLetterBar;

import java.util.List;

import io.reactivex.functions.Consumer;

/**
 * author : robert
 * date   : 2021/5/14 14:19
 * desc   :城市选择
 */
public class CityPickerListActivity extends BaseActivity {
    private ListView mListView;
    private ListView mResultListView;
    private SideLetterBar mLetterBar;
    private EditText searchBox;
    private ImageView clearBtn;
    private ViewGroup emptyView;
    private ActivityTitle mActivityTitle;


    private CityListAdapter mCityAdapter;
    private ResultListAdapter mResultAdapter;
    private List<City> mAllCities;
    private DBManager dbManager;

    private AMapLocationClient mLocationClient;

    @Override
    public int getLayout() {
        return R.layout.activity_city_picker_list;
    }

    @Override
    public void initView() {
        super.initView();
        initDb();

        mActivityTitle = (ActivityTitle) findViewById(R.id.activity_title);
        immersiveStatusBar(mActivityTitle.getView());
        mListView = (ListView) findViewById(R.id.listview_all_city);
        mListView.setAdapter(mCityAdapter);

        TextView overlay = (TextView) findViewById(R.id.tv_letter_overlay);
        mLetterBar = (SideLetterBar) findViewById(R.id.side_letter_bar);
        mLetterBar.setOverlay(overlay);
        mLetterBar.setOnLetterChangedListener(new SideLetterBar.OnLetterChangedListener() {
            @Override
            public void onLetterChanged(String letter) {
                int position = mCityAdapter.getLetterPosition(letter);
                mListView.setSelection(position);
            }
        });

        searchBox = (EditText) findViewById(R.id.et_search);
        searchBox.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String keyword = s.toString();
                if (TextUtils.isEmpty(keyword)) {
                    clearBtn.setVisibility(View.GONE);
                    emptyView.setVisibility(View.GONE);
                    mResultListView.setVisibility(View.GONE);
                } else {
                    clearBtn.setVisibility(View.VISIBLE);
                    mResultListView.setVisibility(View.VISIBLE);
                    List<City> result = dbManager.searchCity(keyword);
                    if (result == null || result.size() == 0) {
                        emptyView.setVisibility(View.VISIBLE);
                    } else {
                        emptyView.setVisibility(View.GONE);
                        mResultAdapter.changeData(result);
                    }
                }
            }
        });

        emptyView = (ViewGroup) findViewById(R.id.empty_view);
        mResultListView = (ListView) findViewById(R.id.listview_search_result);
        mResultListView.setAdapter(mResultAdapter);
        mResultListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String name = mResultAdapter.getItem(position).getName();
                String code = mResultAdapter.getItem(position).getCode();
                Intent intent = new Intent();
                intent.putExtra("city_name", name);
                intent.putExtra("city_code", code);
                setResult(RESULT_OK, intent);
                finish();
            }
        });

        clearBtn = (ImageView) findViewById(R.id.iv_search_clear);
        clearBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                searchBox.setText("");
                clearBtn.setVisibility(View.GONE);
                emptyView.setVisibility(View.GONE);
                mResultListView.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void initData() {
        super.initData();
        initLocationPermission();
    }

    //高德定位权限
    private void initLocationPermission() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        LogUtils.d("aBoolean:" + aBoolean);
                        if (aBoolean) {
                            initLocation();
                        } else {
                            ToastUtils.showText(getString(R.string.string_no_permission));
                        }
                    }
                });
    }


    @Override
    public void initListener() {
        super.initListener();
        mActivityTitle.setBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void initLocation() {
        mLocationClient = new AMapLocationClient(this);
        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setOnceLocation(true);
        mLocationClient.setLocationOption(option);
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        String city = aMapLocation.getCity();
                        String district = aMapLocation.getDistrict();
                        Log.e("onLocationChanged", "city: " + city);
                        Log.e("onLocationChanged", "district: " + district);
                        String location = PickerStringUtils.getLocation(city, district);
                        mCityAdapter.updateLocateState(LocateState.SUCCESS, location, aMapLocation.getAdCode());
                    } else {
                        //定位失败
                        mCityAdapter.updateLocateState(LocateState.FAILED, null, null);
                    }
                }
            }
        });
        mLocationClient.startLocation();
    }

    private void initDb() {
        dbManager = new DBManager(this);
        dbManager.copyDBFile();
        mAllCities = dbManager.getAllCities();
        mCityAdapter = new CityListAdapter(this, mAllCities);
        mCityAdapter.setOnCityClickListener(new CityListAdapter.OnCityClickListener() {
            @Override
            public void onCityClick(String name, String code) {
                Intent intent = new Intent();
                intent.putExtra("city_name", name);
                intent.putExtra("city_code", code);
                setResult(RESULT_OK, intent);
                finish();
            }

            @Override
            public void onLocateClick() {
                Log.e("onLocateClick", "重新定位...");
                mCityAdapter.updateLocateState(LocateState.LOCATING, null, null);
                if (mLocationClient != null)
                    mLocationClient.startLocation();
            }
        });

        mResultAdapter = new ResultListAdapter(this, null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onPageStart(this, "赛事城市选择界面");
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPageEnd(this, "赛事城市选择界面");
    }
}
